<template>
  <div class="content-container">
    <el-form size="large" label-width="100px">
      <el-form-item label="姓名">
        <el-input ref="nameInput" v-model="formData.name" />
      </el-form-item>
      <el-form-item label="来访日期">
        <el-date-picker
          v-model="formData.enterDate"
          type="date"
          placeholder="Pick a day"
          :clearable="false"
          :disabled="outputData.visitorName == ''"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="来访时间">
        <!-- <el-divider direction="vertical" /> -->
        <el-time-select
          v-model="formData.enterTime"
          start="0:00"
          step="00:30"
          end="24:00"
          placeholder="Select time"
          :clearable="false"
          :disabled="outputData.visitorName == ''"
          style="width: 100%"
          @change="handleEnterTimeChange"
        />
      </el-form-item>
      <el-form-item label="来访时长">
        <el-select
          v-model="formData.duration"
          style="width: 100%"
          @change="handleDurationChange"
          :disabled="outputData.visitorName == ''"
        >
          <el-option
            v-for="i in 48"
            :label="`${i * 0.5} 小时`"
            :value="i * 30"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="离开时间">
        <el-time-select
          v-model="formData.leaveTime"
          start="0:00"
          step="00:30"
          end="24:00"
          placeholder="Select time"
          :clearable="false"
          :disabled="outputData.visitorName == ''"
          style="width: 100%"
          @change="handleLeaveTimeChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :disabled="
            outputData.visitorName == '' || outputData.visitDuration <= 0
          "
          @click="handleAdd"
        >
          <el-icon><Pointer /></el-icon>
          <span>提交</span>
          <span
            v-if="outputData.crossDay"
            style="font-size: 12px; margin-left: 12px; opacity: 0.6"
          >
            (+1天)
          </span>
        </el-button>
        <!-- <el-button type="danger" v-else disabled> 错误 </el-button> -->
      </el-form-item>
    </el-form>
    <pre class="json-container">{{ outputData }}</pre>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import dayjs from "dayjs";
// import useCommonStore from "@/store/common.js";

// const commonStore = useCommonStore();
// const darkMode = computed(() => commonStore.darkMode);

const emits = defineEmits(["success"]);

const resetTimer = ref();
onMounted(() => {
  intiFormData();
  if (!resetTimer.value) {
    resetTimer.value = setInterval(() => {
      if (formData.value.name.length == 0) {
        intiFormData();
      }
    }, 500);
  }
});

onUnmounted(() => {
  if (!resetTimer.value) {
    clearInterval(resetTimer.value);
    resetTimer.value = null;
  }
});

const nameInput = ref();

const formData = ref({
  name: "",
  enterDate: new Date(),
  enterTime: "00:00",
  leaveTime: "00:00",
  duration: 60,
  resetTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
});

const intiFormData = () => {
  formData.value.name = "";
  formData.value.resetTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
  let duration = 60;
  formData.value.duration = duration;
  let enter = dayjs();
  let leave = dayjs().add(duration, "minute");
  let minute = Math.floor(enter.format("mm") / 30) * 30;
  formData.value.enterTime =
    enter.format("HH") + ":" + (minute < 10 ? "0" : "") + minute;
  formData.value.leaveTime =
    leave.format("HH") + ":" + (minute < 10 ? "0" : "") + minute;
  if (nameInput.value) {
    nameInput.value.focus();
  }
};

const outputData = computed(() => {
  let enter = dayjs(
    dayjs(formData.value.enterDate).format("YYYY-MM-DD") +
      " " +
      formData.value.enterTime +
      ":00"
  );
  let leave = dayjs(
    dayjs(formData.value.enterDate).format("YYYY-MM-DD") +
      " " +
      formData.value.leaveTime +
      ":00"
  );
  let duration = leave.diff(enter, "minute");
  let crossDay = false;
  if (duration < 0) {
    leave = leave.add(1, "day");
    // duration += 1440;
    duration = leave.diff(enter, "minute");
    crossDay = true;
  }
  return {
    visitorName: formData.value.name,
    enterTime: enter.format("YYYY-MM-DD HH:mm:ss"),
    leaveTime: leave.format("YYYY-MM-DD HH:mm:ss"),
    visitDuration: duration,
    reset: formData.value.resetTime,
    crossDay,
  };
});

const handleEnterTimeChange = () => {
  formData.value.leaveTime = dayjs(outputData.value.enterTime)
    .add(formData.value.duration, "minute")
    .format("HH:mm");
  // formData.value.leaveTime = outputData.value.leaveTime;
  console.log("handleEnterTimeChange");
};
const handleLeaveTimeChange = () => {
  // formData.value.duration = dayjs(outputData.value.leaveTime).diff(
  //   outputData.value.enterTime,
  //   "minute"
  // );
  formData.value.duration = outputData.value.visitDuration;
  console.log("handleLeaveTimeChange");
};
const handleDurationChange = () => {
  formData.value.leaveTime = dayjs(outputData.value.enterTime)
    .add(formData.value.duration, "minute")
    .format("HH:mm");
  // formData.value.leaveTime = outputData.value.leaveTime;
  console.log(
    "handleDurationChange",
    outputData.value.enterTime,
    formData.value.duration
  );
};

const handleAdd = () => {
  axios
    .post("api/journal_visit.php", { action: "add", input: outputData.value })
    .then((res) => {
      if (res.data == true) {
        ElMessage.success(`已保存${outputData.value.visitorName}的来访信息`);
        intiFormData();
        // emit
        emits("success");
      } else {
        console.warn(
          `保存${outputData.value.visitorName}的来访信息出错了`,
          res
        );
        ElMessage.warning(
          `保存${outputData.value.visitorName}的来访信息出错了`
        );
      }
    })
    .catch((err) => {
      console.error(`保存${outputData.value.visitorName}的来访信息出错了`, err);
      ElMessage.error(`保存${outputData.value.visitorName}的来访信息出错了`);
    });
};
</script>

<style scoped>
@import "@/styles/vibrate.css";
@import "./scopeStyle.css";
</style>
